/*
 * EasyWGetter.cpp
 *
 *  Created on: 2010-4-29
 *      Author: Yupeng
 */

#include <utf.h>
#include <e32err.h>

#include "HttpGetter.h"

_LIT(KDefFile, "tmp.html");
_LIT(KDefDir, "c:\\data\\");
CHttpGetter * CHttpGetter::NewL( const TDesC& aUrl )
	{
	CHttpGetter * self = new (ELeave)CHttpGetter;
	CleanupStack::PushL( self );
	self->ConstructL( aUrl );
	CleanupStack::Pop();
	return self;
	}

CHttpGetter::~CHttpGetter()
	{
	iFile.Close();
	iFs.Close();
	iTransaction.Close();
	iHttp.Close();
	delete iFileName;
	}

CHttpGetter::CHttpGetter()
	{
	}

void CHttpGetter::ConstructL(const TDesC& aUrl)
	{
	User::LeaveIfError( iFs.Connect() );
	CnvUtfConverter::ConvertFromUnicodeToUtf8( iUri, aUrl );
	iHttp.OpenL();
	}

void CHttpGetter::StartGetL()
	{
	RStringF get = iHttp.StringPool().StringF( HTTP::EGET, RHTTPSession::GetTable() );
	TUriParser8 uri;
	uri.Parse( iUri );
	if( !uri.IsPresent( EUriScheme ) )
		{
		iUri.Insert(0, _L8("http://") );
		uri.Parse( iUri );
		}
	HBufC * file = uri.GetFileNameL( EUriFileNameTail );
	if( !file || !file->Length() )
		{
		delete file;
		file = NULL;
		file = HBufC::NewL(128);
		file->Des().Append( KDefFile );
		}
	
	HBufC * path = HBufC::NewL(256);
	path->Des().Append( KDefDir );
	path->Des().Append( *file );
	delete file; 
	file = NULL;
	iFileName = path;
	TInt err = iFile.Create( iFs, *iFileName, EFileWrite );
	if( KErrAlreadyExists == err )
		{
		err = iFile.Open( iFs, *iFileName, EFileWrite ) ;
		}
	User::LeaveIfError( err );
	iFile.SetSize( 0 );

	iTransaction = iHttp.OpenTransactionL( uri, *this, get );
	iTransaction.SubmitL();	
	}

void CHttpGetter::MHFRunL( RHTTPTransaction aTransaction, const THTTPEvent& aEvent )
	{
	switch( aEvent.iStatus )
		{
		case THTTPEvent::EGotResponseHeaders:
			break;
		case THTTPEvent::EGotResponseBodyData:
			MHTTPDataSupplier * body = aTransaction.Response().Body();
			TPtrC8 dataChunk;
			TBool last = body->GetNextDataPart(dataChunk);
			iFile.Write( iPos, dataChunk );
			body->ReleaseData();
			iPos += dataChunk.Length();
			if( last )
				{
				CActiveScheduler::Stop();
				}
			break;
		case THTTPEvent::EFailed:
			CActiveScheduler::Stop();
			break;
		default:
			break;
		}
	}

TInt CHttpGetter::MHFRunError( TInt /* aError */, RHTTPTransaction /*aTransaction*/, 
		const THTTPEvent& /*aEvent*/ )
	{
	CActiveScheduler::Stop();
	return KErrNone;
	}

